#pragma once
// 写一个服务端和客户端利用fifo通信的程序

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
#include <memory> // RAII

class MakeFifo
{
public:
    using ptr = std::shared_ptr<MakeFifo>;
    MakeFifo(const std::string &path, const std::string &name)
    {
        umask(0); // 设置权限掩码
        std::string str = path + (path.back() == '/' ? "" : "/") + name;
        _fifoName = str;
        int n = mkfifo(str.c_str(), 0666); // 创建管道文件，输入路径和权限
        if (n < 0)
        {
            std::cerr << "mkfifo error\n";
        }
        else
        {
            std::cout << "mkfifo sucess" << std::endl;
        }
    }
    std::string name()
    {
        return _fifoName;
    }
    ~MakeFifo()
    {
        int n = unlink(_fifoName.c_str());
        if (n == 0)
        {
            std::cout << "unlink sucess" << std::endl;
        }
        else
        {
            std::cout << "remove fifo failed" << std::endl;
        }
    }

private:
    std::string _fifoName;
};
class FifoOpener
{
public:
    FifoOpener(const std::string &path, const std::string &name) : _name(path + '/' + name)
    {
    }

    void OpenForRead()
    {
        _fd = open(_name.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open error\n";
        }
        else
        {
            std::cout << "open success" << std::endl;
        }
    }
    void OpenForWrite()
    {
        _fd = open(_name.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open error\n";
            exit(1);
        }
        else
        {
            std::cout << "open success" << std::endl;
        }
    }
    void Read()
    {
        char buff[1024];
        while (true)
        {
            int n = read(_fd, buff, sizeof(buff) - 1); // 如果写端没有打开，阻塞住
            if (n == 0)
            {
                // 读到文件末尾，并且写端关闭
                std::cout << "client quit! me too!" << std::endl;
                //Close();
                break;
            }
            else if (n > 0)
            {
                std::cout << "Clent Say# " << buff << std::endl;
            }
            else
            {
                std::cerr << "unname error\n";
            }
        }
    }
    void Write()
    {
        std::string stream;
        pid_t id = getpid();
        int cnt = 1;
        while (true)
        {
            if (cnt == 5)
            {
                Close();
                break;
            }
            std::cout<< "Please Enter# ";
            std::getline(std::cin, stream);
            stream += (", message number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
            write(_fd, stream.c_str(), stream.size()); // 如果写端没有打开，阻塞住
        }
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }

private:
    std::string _name;
    int _fd;
};

